"""
主动服务API端点
提供主动推荐、预测服务等功能
"""

from fastapi import APIRouter, Depends, Query, HTTPException
from typing import Dict, Any, List, Optional
import uuid
from uuid import UUID

from src.services.proactive_service import ProactiveService
from src.models.user import User
from src.routes.auth import get_current_user
from src.config.database import get_db

router = APIRouter(prefix="/proactive", tags=["主动服务"])

# 初始化服务
proactive_service = ProactiveService()

@router.get("/recommendations", summary="获取主动推荐")
async def get_proactive_recommendations(
    limit: int = Query(5, ge=1, le=20, description="推荐数量"),
    current_user: User = Depends(get_current_user),
    db = Depends(get_db)
):
    """
    根据用户行为和偏好获取主动推荐
    
    Args:
        limit: 推荐数量，默认为5条，最多20条
        current_user: 当前用户对象
        
    Returns:
        主动推荐列表
    """
    try:
        recommendations = await proactive_service.generate_proactive_recommendations(
            UUID(str(current_user.id)), limit
        )
        return {
            "recommendations": recommendations,
            "count": len(recommendations)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取主动推荐失败: {str(e)}")

@router.get("/predictions", summary="获取预测服务")
async def get_predicted_services(
    current_user: User = Depends(get_current_user),
    db = Depends(get_db)
):
    """
    预测用户可能需要的服务
    
    Args:
        current_user: 当前用户对象
        
    Returns:
        预测服务列表
    """
    try:
        predictions = await proactive_service.predict_user_needs(UUID(str(current_user.id)))
        return {
            "predictions": predictions,
            "count": len(predictions)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取预测服务失败: {str(e)}")

@router.post("/recommendations/{recommendation_id}/accept", summary="接受推荐")
async def accept_recommendation(
    recommendation_id: str,
    current_user: User = Depends(get_current_user),
    db = Depends(get_db)
):
    """
    用户接受推荐，用于优化推荐算法
    
    Args:
        recommendation_id: 推荐ID
        current_user: 当前用户对象
        
    Returns:
        操作结果
    """
    try:
        # 记录用户接受推荐的行为，用于优化推荐算法
        # 这里应该调用用户偏好服务更新用户偏好
        return {"message": "推荐接受成功", "recommendation_id": recommendation_id}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"接受推荐失败: {str(e)}")

@router.post("/recommendations/{recommendation_id}/dismiss", summary="忽略推荐")
async def dismiss_recommendation(
    recommendation_id: str,
    current_user: User = Depends(get_current_user),
    db = Depends(get_db)
):
    """
    用户忽略推荐，用于优化推荐算法
    
    Args:
        recommendation_id: 推荐ID
        current_user: 当前用户对象
        
    Returns:
        操作结果
    """
    try:
        # 记录用户忽略推荐的行为，用于优化推荐算法
        return {"message": "推荐忽略成功", "recommendation_id": recommendation_id}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"忽略推荐失败: {str(e)}")

@router.post("/notifications/test", summary="测试通知发送")
async def test_notification(
    notification_data: Dict[str, Any],
    current_user: User = Depends(get_current_user),
    db = Depends(get_db)
):
    """
    测试主动通知发送功能
    
    Args:
        notification_data: 通知内容
        current_user: 当前用户对象
        
    Returns:
        发送结果
    """
    try:
        success = await proactive_service.send_proactive_notification(
            UUID(str(current_user.id)), 
            notification_data
        )
        return {
            "message": "通知发送成功" if success else "通知发送失败",
            "success": success
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"测试通知发送失败: {str(e)}")